import React, { memo, useEffect, useCallback } from "react";
import Slider from "../../components/slider";
import { connect } from 'react-redux';
import * as actionTypes from './store/actionCreators';
import Scroll from '../../baseUI/scroll/index';
import RecommenList from '../../components/list';
import {Content} from './style';
import {forceCheck} from 'react-lazyload';
import Loading from '../../baseUI/loading/index';
import { renderRoutes } from "react-router-config";

function Recommend(props) {
  const {bannerList, recommendList, enterLoading} = props
  const {getBannerDataDispatch, getRecommendListDataDispatch} = props

  useEffect(() => {
    if(!bannerList.size) {
      getBannerDataDispatch()
    }
  }, [bannerList.size, getBannerDataDispatch])

  useEffect(() => {
    if(!recommendList.size) {
      getRecommendListDataDispatch()
    }
  }, [recommendList.size, getRecommendListDataDispatch])

  const bannerListJS = bannerList ? bannerList.toJS() : []
  const recommendListJS = recommendList ? recommendList.toJS() : []

  return (
    <Content>
      <Scroll className="list" onSroll={forceCheck}>
      <div>
          <Slider bannerList={bannerListJS}></Slider>
          <RecommenList recommendList={recommendListJS}></RecommenList>
      </div>
      </Scroll>
      {enterLoading && <Loading></Loading>}
      {/* 将目前所在路由的下一层子路由加以渲染 */}
      {renderRoutes(props.route.routes)}
    </Content>
  )
}

// 映射 Redux 全局的 state 到组件的 props 上
const mapStateToProps = (state) => ({
  bannerList: state.getIn(['recommend', 'bannerList']),
  recommendList: state.getIn(['recommend', 'recommendList']),
  enterLoading: state.getIn(['recommend', 'enterLoading']),
})

// 映射 dispatch 到 props 上
const mapDispatchToProps = (dispatch) => {
  return {
    getBannerDataDispatch() {
      dispatch(actionTypes.getBannerList())
    },
    getRecommendListDataDispatch() {
      dispatch(actionTypes.getRecommendList())
    },
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(memo(Recommend));
